__author__ = 'tyrion'

import  requests
import  json
from  conf.gloal import SALT_MASTER_IP


# class SaltHelper:
#     def __init__(self):
#         self.saltMaster = ""
#
#     def GetToken():
#         headers = {'content-type': 'application/json'}
#         para = {"username": "saltapi_gboss", "password": "nd.com.cn..pw", "eauth": "pam"}
#         url = "http://%s/login" % ()
#         print url
#
#         r = requests.post(url, data=json.dumps(para), headers=headers)
#         # print r.text
#         jsonRet = r.json()
#         result = jsonRet.get('return', "not found result")
#         token = result[0].get("token", "not found token")
#         # print(token)
#         return token




def GetToken(saltMaster = SALT_MASTER_IP):
    headers = {'content-type': 'application/json'}
    para = {"username": "saltapi_gboss", "password": "nd.com.cn..pw", "eauth": "pam"}
    # url = "http://%s/login" % (SALT_MASTER_IP)
    url = "http://%s/login" % (saltMaster)
    print url

    r = requests.post(url, data=json.dumps(para), headers=headers)
    # print r.text
    jsonRet = r.json()
    result = jsonRet.get('return', "not found result")
    token = result[0].get("token", "not found token")
    # print(token)
    return token


def ExecuteCommand(target, cmd, saltMaster = SALT_MASTER_IP):
    print("info: salt execute command cmd =%s, target = %s"%(cmd, target))
    token = GetToken(saltMaster)
    headers = {'content-type': 'application/json', 'X-Auth-Token': token}

    tgt = "ipv4:%s" % (target)
    para = {"client":"local", "tgt":tgt, "fun":"gboss.exec_cmd" ,"arg": cmd , "expr_form": "grain"}
    url = 'http://%s/' % (saltMaster)

    r = requests.post(url, data=json.dumps(para), headers=headers)
    print "info: %s"% r.text
    # print(r.json())

    return (r.json())

def TransFile(filePath, targetPath):
    print ("info: salt transform file = %s"%filePath)
    return


def AnalyseResult(retMsg, errMsg, hostIp):
    Msg = retMsg.get("return")
    if len(Msg[0]) == 0:
            print ("error: this machine=%s is not under salt manage" %hostIp)
            return 'false'
    for  k, v in Msg[0].items():
        # print v
        status = v.get("success")
        # print( status)
        if status == "false":
            print("error: %s" % errMsg)
            return "false"
    return  status

if __name__ == '__main__':
    GetToken()
    # ExecuteCommand("221.228.81.135", "ls /var")